package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.Movements;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.pojo.VisitorsVo;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: cloudy
 * @Description:
 * @Date: Created in 17:40 2021/1/6
 * @ModifiedBy:
 */
@Service
public class MovementsService {

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    public String savePublish(String textContent, MultipartFile[] imageContent, String location, String longitude, String latitude) {
        //第一步还是校验token
        User user = UserThreadLocal.get();

        //封装一个publish对象,并调用dubbo当中的服务
        Publish publish = new Publish();
        publish.setText(textContent);
        publish.setLocationName(location);
        publish.setLatitude(latitude);
        publish.setLongitude(longitude);
        publish.setUserId(user.getId());
        publish.setSeeType(1);//后期要改再改

        List<String> picUrlList = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            PicUploadResult picUploadResult = this.picUploadService.upload(multipartFile);
            picUrlList.add(picUploadResult.getName());
        }
        publish.setMedias(picUrlList);
        return this.quanZiApi.savePublish(publish);
    }

    @Autowired
    private UserInfoService userInfoService;

    public PageResult queryPublishList(User user, Integer page, Integer pageSize) {
        //获取user的id
        Long userId = null;//默认是null是查询推荐动态

        PageResult pageResult = new PageResult();
        PageInfo pageInfo = null;

        if (user == null) {//推荐动态逻辑处理
            //如果传进来的user为空,则为当前用户查询推荐动态
            //1 先从redis中进行命中
            String value = this.redisTemplate.opsForValue().get("QUANZI_PUBLISH_RECOMMEND_" + UserThreadLocal.get().getId());
            if (StringUtils.isNotEmpty(value)) {
                //如果不为空,则对获取到的value进行处理 注:value中存放的是pid
                String[] pidList = StringUtils.split(value, ",");
                //由于我们需要进行分页处理,可能会出现索引越界问题,因此我们需要对这些进行判断
                int startIndex = (page - 1) * pageSize;
                //如果起始索引小于查询到的集合大小,才进行接下来的操作
                if (startIndex < pidList.length) {
                    int endIndex = page * pageSize - 1;
                    if (endIndex >= pidList.length) {//如果结束索引越界,赋值为集合长度减一
                        endIndex = pidList.length - 1;
                    }

                    List<Long> pids = new ArrayList<>();
                    for (int i = startIndex; i <= endIndex; i++) {
                        pids.add(Long.valueOf(pidList[i]));
                    }

                    List<Publish> publishList = this.quanZiApi.queryPublishByPids(pids);
                    pageInfo = new PageInfo();
                    pageInfo.setRecords(publishList);

                }
            }
        }

        if (null == pageInfo) {
            if (user != null) {
                userId = user.getId();
            }
            pageInfo = this.quanZiApi.queryPublishList(userId, page, pageSize);
        }


        pageResult.setPagesize(pageSize);
        pageResult.setPage(page);
        pageResult.setCounts(0);
        pageResult.setPages(0);

        List<Publish> records = pageInfo.getRecords();

        if (CollectionUtils.isEmpty(records)) {
            //没有动态信息
            return pageResult;
        }

        if (CollectionUtils.isEmpty(records)) {
            // 没有查询到动态数据
            return pageResult;
        }

        pageResult.setItems(this.getMovements(records));

        return pageResult;

    }


    public PageResult queryUserPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(UserThreadLocal.get(), page, pageSize);
    }

    public PageResult queryRecommendPublishList(Integer page, Integer pageSize) {
        return this.queryPublishList(null, page, pageSize);
    }

    //long 返回点赞数
    public Long likeComment(String publishId) {
        //直接调用dubbo，进行点赞操作,返回值是false则直接返回null
        boolean b = this.quanZiApi.saveLikeComment(UserThreadLocal.get().getId(), publishId);
        if (!b) {
            return null;
        }
        //往redis里面存当前用户点赞信息，以及点赞数+1
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        if (this.redisTemplate.hasKey(likeCommentKey)) {
            return this.redisTemplate.opsForValue().increment(likeCommentKey);//redis中有这个key,直接将值加一
        }
        //如果redis里面没有这个key，去查询dubbo，获取点赞数,并存到redis中
        Long likeCount = this.quanZiApi.queryCommentCount(publishId, 1);
        this.redisTemplate.opsForValue().set(likeCommentKey, likeCount.toString());

        // 记录当前用于已经点赞 走到这里就说明他一定没有点过赞，直接保存
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(likeUserCommentKey, "1");
        return likeCount;
    }


    public Long disLikeComment(String publishId) {
        //remove type=1
        boolean b = this.quanZiApi.removeComment(UserThreadLocal.get().getId(), publishId, 1);
        if (!b) {
            //保存失败
            return null;
        }
        //不需要再去判断有没有对应的redisKey，因为取消就代表点过赞了
        String likeCommentKey = "QUANZI_COMMENT_LIKE_" + publishId;
        Long likeCount = this.redisTemplate.opsForValue().decrement(likeCommentKey);

        // 删除该用户的标记点赞
        String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.delete(likeUserCommentKey);
        return likeCount;
    }

    public Long loveComment(String publishId) {
        boolean b = this.quanZiApi.saveLoveComment(UserThreadLocal.get().getId(), publishId);
        if (!b) {
            return null;
        }
        //先查询redis中当前动态有无喜欢数
        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        if (this.redisTemplate.hasKey(loveCommentKey)) {
            return this.redisTemplate.opsForValue().increment(loveCommentKey);
        }

        //没有则调用dubbo查询喜欢数,并存入redis中
        Long count = this.quanZiApi.queryCommentCount(publishId, 3);
        this.redisTemplate.opsForValue().set(loveCommentKey, count.toString());

        // 记录当前用于已经喜欢
        String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.opsForValue().set(loveUserCommentKey, "1");

        return count;
    }

    public Long unLoveComment(String publishId) {
        boolean b = this.quanZiApi.removeComment(UserThreadLocal.get().getId(), publishId, 3);
        if (!b) {
            return null;
        }

        String loveCommentKey = "QUANZI_COMMENT_LOVE_" + publishId;
        Long count = this.redisTemplate.opsForValue().decrement(loveCommentKey);

        // 记录当前用于已经喜欢
        String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + publishId;
        this.redisTemplate.delete(loveUserCommentKey);

        return count;
    }

    /**
     * 抽取公共方法
     * 填充movements
     *
     * @param publishId
     * @return
     */
    public Movements queryMovementsById(String publishId) {
        //先调用dubbo服务，查询出单条发布的信息,如果为null直接返回
        Publish publish = this.quanZiApi.queryPublishById(publishId);
        if (publish == null) {
            return null;
        }
        //将Publish转换为Movements,要抽取方法
        /*List<Publish> records = new ArrayList<>();
        records.add(publish);*/
        List<Movements> movements = getMovements(Arrays.asList(publish));

        return movements.get(0);

    }

    private List<Movements> getMovements(List<Publish> records) {
        //将publishList转换为movementsList
        List<Movements> movementsList = new ArrayList<>();
        Set<Long> userIds = new HashSet<>();
        for (Publish record : records) {
            Movements movements = new Movements();
            movements.setId(record.getId().toHexString());
            movements.setUserId(record.getUserId());

            userIds.add(record.getUserId());//将用户id放到单独的集合里

            String likeUserCommentKey = "QUANZI_COMMENT_LIKE_USER_" + UserThreadLocal.get().getId() + "_" + record.getId().toHexString();
            movements.setHasLiked(this.redisTemplate.hasKey(likeUserCommentKey) ? 1 : 0); //是否点赞
            String likeCommentKey = "QUANZI_COMMENT_LIKE_" + record.getId().toHexString();
            String value = this.redisTemplate.opsForValue().get(likeCommentKey);
            if (StringUtils.isNotEmpty(value)) {
                movements.setLikeCount(Integer.valueOf(value)); //点赞数
            } else {
                movements.setLikeCount(0); //点赞数
            }


            String loveUserCommentKey = "QUANZI_COMMENT_LOVE_USER_" + UserThreadLocal.get().getId() + "_" + movements.getId();
            movements.setHasLoved(this.redisTemplate.hasKey(loveUserCommentKey) ? 1 : 0); //是否喜欢
            String loveCommentKey = "QUANZI_COMMENT_LOVE_" + movements.getId();
            String loveValue = this.redisTemplate.opsForValue().get(loveCommentKey);
            if (StringUtils.isNotEmpty(loveValue)) {
                movements.setLoveCount(Integer.valueOf(loveValue)); //喜欢数
            } else {
                movements.setLoveCount(0); //喜欢数
            }

            movements.setDistance("1.2公里");//TODO 距离
            movements.setCommentCount(10);//评论数this.queryMovementsById(record.getId().toHexString()).getCommentCount()
            movements.setImageContent(record.getMedias().toArray(new String[]{}));
            movements.setTextContent(record.getText());
            movements.setCreateDate(RelativeDateFormat.format(new Date(record.getCreated())));//发布时间

            movementsList.add(movements);
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);
        for (Movements movements : movementsList) {
            for (UserInfo userInfo : userInfoList) {
                if (movements.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    movements.setAge(userInfo.getAge());
                    movements.setAvatar(userInfo.getLogo());
                    movements.setGender(userInfo.getSex().name().toLowerCase());
                    movements.setNickname(userInfo.getNickName());
                    movements.setTags(StringUtils.split(userInfo.getTags(), ','));
                    break;
                }
            }
        }
        return movementsList;
    }

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    /**
     * 查询谁看过我
     */
    public List<VisitorsVo> queryVisitorsList() {
        User user = UserThreadLocal.get();
        String redisKey = "visitor_date_" + user.getId();
        //先从redis中进行命中
        String value = this.redisTemplate.opsForValue().get(redisKey);
        // 如果redis中存在上次查询的时间，就按照这个时间之后查询，如果没有就查询前5个
        List<Visitors> visitorsList = null;
        if (StringUtils.isEmpty(value)) {
            visitorsList = this.visitorsApi.topVisitor(user.getId(), 5);
        } else {
            visitorsList = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(value));
        }
        //如果查询到的集合为空，则直接返回
        if (CollectionUtils.isEmpty(visitorsList)) {
            return Collections.emptyList();
        }

        List<Long> userIds = visitorsList.stream().map(Visitors::getVisitorUserId).collect(Collectors.toList());

//        通过查询mysql,然后填充数据

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoList(queryWrapper);

        List<VisitorsVo> visitorsVoList = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            for (UserInfo userInfo : userInfoList) {
                if (userInfo.getUserId().longValue() == visitors.getVisitorUserId().longValue()) {
                    VisitorsVo visitorsVo = new VisitorsVo();
                    visitorsVo.setAge(userInfo.getAge());
                    visitorsVo.setAvatar(userInfo.getLogo());
                    visitorsVo.setGender(userInfo.getSex().name().toLowerCase());
                    visitorsVo.setId(userInfo.getUserId());
                    visitorsVo.setNickname(userInfo.getNickName());
                    visitorsVo.setTags(StringUtils.split(userInfo.getTags(), ','));
                    visitorsVo.setFateValue(visitors.getScore().intValue());

                    visitorsVoList.add(visitorsVo);
                    break;
                }
            }
        }

        return visitorsVoList;
    }

    public PageResult queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setPages(0);
        pageResult.setCounts(0);

        PageInfo<Publish> albumPageInfo = this.quanZiApi.queryAlbumList(userId, page, pageSize);
        List<Publish> records = albumPageInfo.getRecords();

        if (CollectionUtils.isEmpty(records)){
            return pageResult;
        }

        List<Movements> movements = this.getMovements(records);
        pageResult.setItems(movements);

        return pageResult;
    }
}
